package handlers

import (
	"car-info-sys/cache"
	"car-info-sys/moderls"
	"car-info-sys/pkg"
	"encoding/json"
	"github.com/gin-gonic/gin"
	"strconv"
	"time"
)

func Login(c *gin.Context) {
	username := c.PostForm("username")
	password := c.PostForm("password")
	if username == "" || password == "" {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "字段不可为空",
		})
		return
	}

	redis_key := "login_err" + username
	errCount, _ := cache.Rdb.Get(cache.Ctx, redis_key).Int()
	if errCount >= 3 {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "密码错误三次,禁止登录",
		})
		return
	}

	var user moderls.User
	err := moderls.DB.Where("username=?", username).Find(&user).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "用户名不存在或密码错误",
		})
		return
	}
	if user.ID == 0 {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "用户名不存在",
		})
		return
	}

	if user.Password != pkg.Md5(password) {

		cache.Rdb.Incr(cache.Ctx, redis_key)

		if errCount == 2 {
			cache.Rdb.Set(cache.Ctx, redis_key, 3, time.Hour*2)
			c.JSON(200, gin.H{
				"code": 500,
				"msg":  "密码错误3次,封禁两个小时",
			})
			return
		}

		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "密码错误",
		})
		return
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "登陆成功",
		"data": user,
	})
	return
}

func RoleNodeAdd(c *gin.Context) {
	rid, _ := strconv.Atoi(c.PostForm("rid"))
	nid, _ := strconv.Atoi(c.PostForm("nid"))
	data := moderls.RoleNode{
		Rid: rid,
		Nid: nid,
	}
	moderls.DB.Create(&data)
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "添加成功",
	})
	return
}

func UserRoleList(c *gin.Context) {
	uid := c.Query("uid")
	var role []moderls.Role
	/*
		SELECT
		  *
		FROM
		  roles
		  LEFT JOIN user_roles ON user_roles.rid = roles.id
		WHERE
		  user_roles.uid = 1
	*/
	moderls.DB.Table("roles").
		Joins("LEFT JOIN user_roles ON user_roles.rid = roles.id").
		Where("user_roles.uid = ?", uid).Find(&role)

	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "查询成功",
		"data": role,
	})
	return
}

func RoleNodeList(c *gin.Context) {
	rid := c.Query("rid")
	var node []moderls.Node

	/*
		SELECT
		*
		FROM
		nodes
		LEFT JOIN role_nodes on nodes.id=role_nodes.nid
		WHERE role_nodes.rid=1
	*/

	moderls.DB.Table("nodes").
		Joins("LEFT JOIN role_nodes on nodes.id=role_nodes.nid").
		Where("role_nodes.rid=?", rid).Find(&node)

	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "查询成功",
		"data": node,
	})
	return
}

func CarAdd(c *gin.Context) {
	car_no := c.PostForm("car_no")
	car_name := c.PostForm("car_name")
	car_price := c.PostForm("car_price")
	if car_no == "" || car_name == "" || car_price == "" {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "字段不可为空",
		})
		return
	}

	data := moderls.Car{
		CarNO:    car_no,
		CarName:  car_name,
		CarPrice: car_price,
	}

	moderls.DB.Create(&data)
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "添加成功",
	})
	return
}

func CarTypeAdd(c *gin.Context) {
	type_name := c.PostForm("type_name")
	type_commit := c.PostForm("type_commit")
	type_num, _ := strconv.Atoi(c.PostForm("type_num"))
	cid, _ := strconv.Atoi(c.PostForm("cid"))

	if type_name == "" || type_commit == "" || type_num == 0 || cid == 0 {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "字段不可为空",
		})
		return
	}

	data := moderls.CarType{
		TypeName:   type_name,
		TypeCommit: type_commit,
		TypeNum:    type_num,
		Cid:        cid,
	}

	moderls.DB.Create(&data)

	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "添加成功",
	})
	return
}

func CarList(c *gin.Context) {
	page, _ := strconv.Atoi(c.DefaultQuery("page", "1"))
	size, _ := strconv.Atoi(c.DefaultQuery("size", "2"))
	offset := (page - 1) * size

	var car []moderls.CarTypeList

	/*
		SELECT
		  car_types.id as TypeId,
		  cars.car_no as CarNO,
		  cars.car_name as CarName,
		  cars.car_price as CarPrice,
		  car_types.type_name as TypeName,
		  car_types.type_commit as TypeCommit,
		  car_types.type_num as TypeNum
		FROM
		  car_types
		  LEFT JOIN cars ON cars.id = car_types.cid
	*/
	redis_key := "car_list" + strconv.Itoa(page)
	cacheData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if cacheData == "" {
		moderls.DB.Table("car_types").
			Joins("LEFT JOIN cars ON cars.id = car_types.cid").
			Select(
				"car_types.id as TypeId",
				"cars.car_no as CarNO",
				"cars.car_name as CarName",
				"cars.car_price as CarPrice",
				"car_types.type_name as TypeName",
				"car_types.type_commit as TypeCommit",
				"car_types.type_num as TypeNum",
			).Offset(offset).Limit(size).Debug().Find(&car)
		jsonData, _ := json.Marshal(car)
		cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(cacheData), &car)
	}

	var total int64
	moderls.DB.Model(&moderls.Car{}).Count(&total)

	c.JSON(200, gin.H{
		"code":  200,
		"msg":   "查询成功",
		"data":  car,
		"total": total,
	})
	return
}

func CarDetail(c *gin.Context) {

	id := c.Query("id")

	var car moderls.CarTypeList

	/*
		SELECT
		  car_types.id as TypeId,
		  cars.car_no as CarNO,
		  cars.car_name as CarName,
		  cars.car_price as CarPrice,
		  car_types.type_name as TypeName,
		  car_types.type_commit as TypeCommit,
		  car_types.type_num as TypeNum
		FROM
		  car_types
		  LEFT JOIN cars ON cars.id = car_types.cid
	*/
	redis_key := "car_Detail" + id
	cacheData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if cacheData == "" {
		moderls.DB.Table("car_types").
			Joins("LEFT JOIN cars ON cars.id = car_types.cid").
			Select(
				"car_types.id as TypeId",
				"cars.car_no as CarNO",
				"cars.car_name as CarName",
				"cars.car_price as CarPrice",
				"car_types.type_name as TypeName",
				"car_types.type_commit as TypeCommit",
				"car_types.type_num as TypeNum",
			).Where("car_types.id=?", id).Debug().First(&car)
		jsonData, _ := json.Marshal(car)
		cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(cacheData), &car)
	}

	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "查询成功",
		"data": car,
	})
	return
}
